from datetime import datetime
from dateutil.relativedelta import relativedelta
from models.RentRecord import RentRecord

from flask import  Blueprint,Response,render_template,url_for,request,redirect,jsonify,session
from pandas._version import render
from sqlalchemy import text, select
from flask_mail import Mail, Message


from models.House import House
from models.User import User
from settiings  import db
import json
import time
import uuid
import random # 导入 random 用于生成验证码

bp = Blueprint('user_page', __name__)


@bp.route('/register',methods=['POST'])
def register():
#从表单中获取用户注册信息
    name = request.form['username']
    password = request.form['password']
    email = request.form['email']
#查询是否有重名
    result = User.query.filter(User.name == name).all()
    if len(result) == 0: #没有查到同名用户
      user = User(name=name, password=password, email=email)
      db.session.add(user)
      db.session.commit()
      json_str = json.dumps({'valid':'1','msg':user.name})
      res = Response(json_str)
      res.set_cookie('is_logged_in', 'true', 3600 * 2)
      res.set_cookie('username',user.name, 3600 * 2)
      result = User.query.filter(User.name == user.name).all()
      res.set_cookie('id',str(result.id), 3600 * 2)
      return res
    else:  # 用户名已经被注册过
      return  jsonify({'valid':'0','msg':'用户已被注册！'})


@bp.route('/login',methods=['POST'])
def login():
    # 从表单中获取用户注册信息
    name = request.form['username']
    password = request.form['password']
    # 查询是否有重名
    result = User.query.filter(User.name == name).first()
    if result: #如果用户存在
        if result.password ==password:
            json_str = json.dumps({'valid':'1','msg':result.name})
            res = Response(json_str)

            res.set_cookie('is_logged_in', 'true', 3600 * 2)
            res.set_cookie('username', result.name, 3600 * 2)
            res.set_cookie('id',str(result.id), 3600 * 2)

            return res
        else:
            return jsonify({'valid': '0', 'msg': '密码不正确!'})
    else:  # 用户名已经被注册过
        return jsonify({'valid': '0', 'msg': '用户不正确!'})

@bp.route('/get_code',methods=['POST'])
def get_code():
    #从表单中获取用户注册信息
    email = request.form['email']
    if not email:
        return jsonify({'valid': '0', 'msg': '邮箱不能为空'})
    
    user = User.query.filter(User.email == email).first()
    if user is None:
        return jsonify({'valid': '0', 'msg': '邮箱不正确'}) # 或者其他提示信息
    
    verification_code = str(random.randint(100000, 999999))
    session[f'email_code_{email}'] = verification_code
    try:
        msg = Message("您的验证码", sender="965492893@qq.com", recipients=[email])
        msg.body = f"您的验证码是: {verification_code}，请在有效期内使用。"
        from app import mail 
        mail.send(msg)
        return jsonify({'valid': '1', 'msg': '验证码发送成功!'})
    except Exception as e:
        print(f"邮件发送失败: {e}")
        return jsonify({'valid': '0', 'msg': '邮件发送失败!'})

@bp.route('/email_login',methods=['POST'])
def email_login():
    #从表单中获取用户注册信息
    email = request.form['email']
    code = request.form['code']
    
    result = User.query.filter(User.email == email).first()
    if result is None: 
        return  jsonify({'valid':'0','msg':'邮箱不正确'})
    
    session_key = f'email_code_{email}'
    stored_code = session.get(session_key)
    print(code)
    print(stored_code)
    if str(code) == str(stored_code): 
        json_str = json.dumps({'valid':'1','msg':result.name})
        res = Response(json_str)
        res.set_cookie('is_logged_in', 'true', 3600 * 2)
        res.set_cookie('username',result.name, 3600 * 2)
        res.set_cookie('id',str(result.id), 3600 * 2)
        return res
    else:  # 验证码错误
      return  jsonify({'valid':'0','msg':'验证码错误'})

# 新增注销路由
@bp.route('/logout')
def logout():
    response = redirect('/')
    response.delete_cookie('is_logged_in', path='/')
    response.delete_cookie('username', path='/')
    return response



@bp.route('/user/<name>')
def user_center(name):
    user = User.query.filter(User.name == name).first()
    if user and request.cookies.get('username') == name:#检查用户是否存在，检查cookies
        """-获取用户收藏，进入数据库查询"""
        collect_id_str = user.collect_id
        collect_house_list=[]
        seen_house_list=[]

        if collect_id_str: #如果字符非空
            collect_id_list = collect_id_str.split(',')
            for hid in collect_id_list:
                house = House.query.get(int(hid))
                collect_house_list.append(house)

        #else: #若字符串空
            """------"""
            """获取用户的浏览记录，进入数据库查询"""
            seen_id_str = user.seen_id  # 获取当前用户的浏览记录
            if seen_id_str:
                seen_id_list = seen_id_str.split(',')
                # 根据房源ID获取对应的房源对象
                for hid in seen_id_list:
                    house = House.query.get(int(hid))
                    seen_house_list.append(house)
        else:
            """------"""
            """获取用户的浏览记录，进入数据库查询"""
            seen_id_str = user.seen_id  # 获取当前用户的浏览记录
            if seen_id_str:
                seen_id_list = seen_id_str.split(',')
                # 根据房源ID获取对应的房源对象
                for hid in seen_id_list:
                    house = House.query.get(int(hid))
                    seen_house_list.append(house)
                print(seen_house_list)
            """------"""
        return render_template('user_page.html', user=user,
                                   collect_house_list=collect_house_list,
                                   seen_house_list=seen_house_list)
    else:
        return redirect(url_for('user_page.login')) 


@bp.route('/user/collect_off', methods=['POST'])
def collect_off():
    name = request.cookies.get('username')
    house_id = request.form.get('house_id')

    # 验证用户
    if not name or not house_id:
        return jsonify({
            'valid': '0',
            'msg': '请先登录'
        }), 401

    try:
        # 查询用户
        user = User.query.filter_by(name=name).first()

        if not user:
            return jsonify({
                'valid': '0',
                'msg': '用户不存在'
            }), 404

        # 构建SQL语句
        sql = text("""
            UPDATE user_info
            SET collect_id = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', collect_id, ','), :house_id_str, ','))
            WHERE name = :name
              AND (collect_id LIKE :like_pattern1 
                   OR collect_id = :house_id 
                   OR collect_id LIKE :like_pattern2 
                   OR collect_id LIKE :like_pattern3)
        """)

        # 执行SQL
        result = db.session.execute(
            sql,
            {
                'name': name,
                'house_id': house_id,
                'house_id_str': f',{house_id},',
                'like_pattern1': f'%,{house_id},%',
                'like_pattern2': f'{house_id},%',
                'like_pattern3': f'%,{house_id}'
            }
        )

        # 提交事务
        db.session.commit()

        # 检查是否有行受影响
        if result.rowcount > 0:
            return jsonify({'valid': '1','msg': '取消收藏成功'})
        else:
            return jsonify({'valid': '0','msg': '该房源未收藏'}), 400

    except Exception as e:
        db.session.rollback()
        return jsonify({'valid': '0','msg': '服务器错误，请重试'}), 500


@bp.route('/del_record', methods=['POST'])
def del_record():
    # 获取用户名
    username = request.cookies.get('username')

    print("delete record")
    # 验证用户
    if not username:
        return jsonify({
            'valid': '0',
            'msg': '请先登录'
        }), 401

    try:
        # 查询用户
        user = User.query.filter_by(name=username).first()

        if not user:
            return jsonify({
                'valid': '0',
                'msg': '用户不存在'
            }), 404

        user.seen_id = ''

        # 提交数据库更改
        db.session.commit()

        return jsonify({
            'valid': '1',
            'msg': '浏览记录已清空'
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'valid': '0',
            'msg': '服务器错误，请重试'
        }), 500

# 收藏房源接口
@bp.route('/user/collect_on', methods=['POST'])
def collect_on():
    house_id = request.form.get('house_id')
    username = request.form.get('username')
    if not house_id or not username:
        return jsonify({
            'valid': '0',
            'msg': '请先登录或参数缺失'
        }), 400
    try:
        user = User.query.filter_by(name=username).first()
        if not user:
            return jsonify({
                'valid': '0',
                'msg': '用户不存在'
            }), 404
        if user.collect_id:
            if str(house_id) not in user.collect_id.split(','):
                user.collect_id += f',{house_id}'
        else:
            user.collect_id = house_id
        db.session.commit()

        return jsonify({
            'valid': '1',
            'msg': '收藏成功'
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'valid': '0',
            'msg': '服务器错误，请重试'
        }), 500

# 添加浏览记录
def add_record(house_id,username):
    user = User.query.filter_by(name=username).first()
    seen_id_list = user.seen_id.split(',') if user.seen_id else []
    if str(house_id) in seen_id_list:
        # 若 house_id 已在列表中，先移除，再添加到头部
        seen_id_list.remove(str(house_id))
        seen_id_list.insert(0, str(house_id))
    else:
        # 若 house_id 不在列表中，添加到头部
        seen_id_list.insert(0, str(house_id))

        # 把列表转换回字符串
    user.seen_id = ','.join(seen_id_list)
    db.session.commit()



@bp.route('/upload_house',methods=['POST'])
def upload():
    username = request.cookies.get('username')
    if not username:
        return jsonify({'valid': '0','msg': '请先登录'})
    data = request.get_json()
    house = House()
    house.title = data['title']
    house.rooms = data['rooms']
    house.area = data['area']
    house.price = data['price']
    house.direction = data['direction']
    house.rent_type = data['rent_type']
    house.region = data['region']
    house.block = data['block']
    house.address = data['address']
    house.traffic = data['traffic']
    house.facilities = data['facilities']
    house.highlights = data['highlights']
    house.matching = data['matching']
    house.travel = data['travel']
    house.phone_num = data['phone_num']

    house.landlord = username

    # 获取当前时间戳
    timestamp = int(time.time())
    # 生成随机字符串
    random_string = str(uuid.uuid4().int)[:10]
    house.publish_time = timestamp
    house.house_num = random_string

    db.session.add(house)
    db.session.commit()
    return jsonify({'valid':'1','msg':'发布成功'}) 

@bp.route('/update_house', methods=['POST'])
def update_house():
    """处理更新已有房源的请求"""
    # 1. 验证用户登录状态，与 upload 逻辑相同
    username = request.cookies.get('username')
    if not username:
        return jsonify({'valid': '0', 'msg': '请先登录'})

    # 2. 获取 JSON 数据，与 upload 逻辑相同
    data = request.get_json()

    # 3. 获取 house_id 并查找数据库中的对象
    house_id = data.get('house_id')
    if not house_id:
        return jsonify({'valid': '0', 'msg': '缺少房源ID，无法更新'}), 400

    # 使用主键查询要更新的房源对象
    house_to_update = House.query.get(house_id)
    if not house_to_update:
        return jsonify({'valid': '0', 'msg': '找不到要更新的房源'}), 404

    # 4. 【安全校验】确认当前用户是该房源的房东
    if house_to_update.landlord != username:
        return jsonify({'valid': '0', 'msg': '没有权限修改此房源'}), 403

    # 5. 用 data 中的数据更新 house_to_update 对象的属性
    try:
        house_to_update.title = data['title']
        house_to_update.rooms = data['rooms']
        house_to_update.area = data['area']
        house_to_update.price = data['price']
        house_to_update.direction = data['direction']
        house_to_update.rent_type = data['rent_type']
        house_to_update.region = data['region']
        house_to_update.block = data['block']
        house_to_update.address = data['address']
        house_to_update.traffic = data['traffic']
        house_to_update.facilities = data['facilities']
        house_to_update.highlights = data['highlights']
        house_to_update.matching = data['matching']
        house_to_update.travel = data['travel']
        house_to_update.phone_num = data['phone_num']

        # 6. 提交会话以保存更改
        db.session.commit()

        # 7. 返回成功的响应
        return jsonify({'valid': '1', 'msg': '更新成功'})

    except Exception as e:
        # 如果在更新或提交过程中发生错误，回滚事务
        db.session.rollback()
        print(f"Error updating house {house_id}: {e}")
        return jsonify({'valid': '0', 'msg': '更新失败，服务器内部错误'}), 500

@bp.route('/user/my_houses',methods=['GET'])
def my_houses():
    username = request.cookies.get('username')
    houses = House.query.filter_by(landlord=username).all()

    houses = [{
        'house_id': house.id,
        'title': house.title,
        'rooms': house.rooms,
        'area': house.area,
        'price': house.price,
        'direction': house.direction,
        'rent_type': house.rent_type,
        'region': house.region,
        'block': house.block,
        'address': house.address,
        'traffic': house.traffic,
        'facilities': house.facilities,
        'highlights': house.highlights,
        'matching': house.matching,
        'travel': house.travel,
        'phone_num': house.phone_num,
        'rent_status': house.rent_status,
    } for house in houses]
    return jsonify({'valid':'1','houses':houses})

@bp.route('/user/my_rent', methods=['GET'])
def my_rent():
    name = request.cookies.get('username')
    if not name:
        return jsonify({'valid': '0', 'msg': '未登录'}), 401
    try:
        # 构建查询
        stmt = (
            select(RentRecord, House)
            .join(House, RentRecord.house_id == House.id, isouter=True)
            .filter(RentRecord.username == name)
        )

        # 执行查询
        result = db.session.execute(stmt)
        rent_records = result.all()  # 获取所有结果
        print(f"查询结果数量: {len(rent_records)}")

        # 处理数据
        houses = []
        for rent_record, house in rent_records:
            record_data = {
                'rent_record_id': rent_record.id,
                'house_id': rent_record.house_id,
                'username': rent_record.username,
                'rent_start_time': rent_record.rent_start_time.strftime('%Y-%m-%d %H:%M:%S') if rent_record.rent_start_time else None,
                'rent_end_time': rent_record.rent_end_time.strftime('%Y-%m-%d %H:%M:%S') if rent_record.rent_end_time else None,
                'currentTime':datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'total_price': rent_record.total_price,
                'house_title': house.title if house else None,
                'house_address': house.address if house else None,
                'house_price': house.price if house else None,
            }
            print(record_data)
            houses.append(record_data)
            houses.reverse()
        return jsonify({'valid': '1', 'msg': '查询成功', 'houses': houses})

    except Exception as e:
        print(e)
        return jsonify({'valid': '0', 'msg': f'查询失败：{str(e)}'}), 500


@bp.route('/user/rent', methods=['POST'])
def rent():
    data = request.get_json()
    name = data['username']
    tMonth = data['month']
    theMonth=int(tMonth)
    house_id = data['house_id']
    house = House.query.filter_by(id=house_id).first()

    price = int(house.price)
    is_rent = house.rent_status

    # 检查房屋是否已经被租出
    if is_rent:
        return jsonify({'valid': '0', 'msg': '房屋已被租借'})

    total_price = price * theMonth
    start_time = datetime.now()
    end_time = start_time + relativedelta(months=theMonth)
    new_record = RentRecord(
        username=name,
        house_id=house_id,
        rent_start_time=start_time,
        rent_end_time=end_time,
        total_price=total_price
    )
    db.session.add(new_record)
    # 更新房屋状态为已租借
    house.rent_status = 1
    db.session.commit()

    return jsonify({'valid': '1', 'msg': '租借成功'})


@bp.route('/user/check_collect', methods=['GET'])
def check_collect():
    house_id = request.args.get('house_id')
    username = request.cookies.get('username')
    house = House.query.filter_by(id=house_id).first()
    if not username or not house_id:
        return jsonify({'valid': '0', 'msg': '请先登录或参数缺失'}), 401

    try:
        user = User.query.filter_by(name=username).first()
        if not user:
            return jsonify({'valid': '0', 'msg': '用户不存在'}), 404

        # 检查用户的collect_id字段是否包含当前房源ID
        is_collected = False
        if user.collect_id:
            is_collected = str(house_id) in user.collect_id.split(',')

        return jsonify({
            'valid': '1',
            'is_collected': is_collected
        })

    except Exception as e:
        return jsonify({'valid': '0', 'msg': '服务器错误，请重试'}), 500


@bp.route('/user/renew_rent', methods=['POST'])
def renew_rent():
    house_id = request.form.get('house_id')
    name = request.form.get('user_name')
    theMonth = int(request.form.get('renew_months'))

    print(house_id)
    # 查询数据
    rent_record = RentRecord.query.filter_by(
        house_id=house_id,
        username=name,
    ).first()

    if not rent_record:
        return jsonify({'valid': '0', 'msg': '未找到租借记录'}), 404

    now = datetime.now()
    start_time = rent_record.rent_start_time
    end_time = rent_record.rent_end_time
    house = House.query.filter_by(id=house_id).first()
    price = int(house.price)  # 将字符串强制转换为整数

    try:
        if end_time <= now:
            total_price = price * theMonth
            new_start_time = datetime.now()
            new_end_time = new_start_time + relativedelta(months=theMonth)
            new_record = RentRecord(
                username=name,
                house_id=house_id,
                rent_start_time=new_start_time,
                rent_end_time=new_end_time,
                total_price=total_price
            )
            db.session.add(new_record)
            db.session.commit()

        else:
            new_end_time = rent_record.rent_end_time + relativedelta(months=theMonth)

            # 更新租借记录
            rent_record.rent_end_time = new_end_time  # 修正字段名
            rent_record.total_price += price * theMonth  # 更新总价格
            rent_record.updated_at = datetime.now()

            # 提交数据库变更
            db.session.commit()

        return jsonify({
            'valid': '1',
            'msg': f'续租成功！已续租{theMonth}个月',
            'data': {
                'new_end_time': new_end_time.strftime('%Y-%m-%d'),
                'renew_price': price * theMonth,
                'monthly_price': price
            }
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'valid': '0', 'msg': str(e)}), 500  # 将异常转换为字符串